package petrochina.company.electric.app;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.google.gson.Gson;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyConfig;
import com.hjq.toast.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tencent.mmkv.MMKV;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.OkHttpClient;
import petrochina.company.electric.R;
import petrochina.company.electric.aop.Log;
import petrochina.company.electric.http.api.LoginApi;
import petrochina.company.electric.http.glide.GlideApp;
import petrochina.company.electric.http.model.RequestHandler;
import petrochina.company.electric.http.model.RequestServer;
import petrochina.company.electric.manager.ActivityManager;
import petrochina.company.electric.manager.ClientManager;
import petrochina.company.electric.other.AppConfig;
import petrochina.company.electric.other.DebugLoggerTree;
import petrochina.company.electric.other.MaterialHeader;
import petrochina.company.electric.other.SmartBallPulseFooter;
import petrochina.company.electric.other.TitleBarStyle;
import petrochina.company.electric.other.ToastLogInterceptor;
import petrochina.company.electric.other.ToastStyle;
import petrochina.company.electric.socket.WebSocketService;
import timber.log.Timber;

/**
 *    desc   : 应用入口
 */
public class AppApplication extends Application {

    private final static String TAG = "webService";

    private static AppApplication instance;
    private static final String DEVICE_TOKEN = "device_token";//设备token
    public WebSocketService mWebSocketService;
    //    -------------------------------------WebSocket发送空消息心跳检测------------------------------------------------
    private static final long HEART_BEAT_RATE = 15 * 1000;//每隔1分钟发送空消息保持WebSocket长连接

    public static AppApplication getInstance() {
        if (instance == null) {
            instance = new AppApplication();
        }
        return instance;
    }
    private Handler mHandler = new Handler();


    private Runnable webSocketRunnable = new Runnable() {
        @Override
        public void run() {
            if (mWebSocketService != null &&
                    mWebSocketService.client != null && mWebSocketService.client.isOpen()) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("from","");
                    jsonObject.put("to", "");

                    android.util.Log.e(TAG, "JSONObject：" + jsonObject.toString());
                    mWebSocketService.sendMsg(jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            //每隔一定的时间，对长连接进行一次心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };


    public WebSocketService getWebSocketService() {
        return mWebSocketService;
    }

    /**
     * 开启并绑定WebSocket服务
     */
    public void startWebSocketService() {
        Intent bindIntent = new Intent(this, WebSocketService.class);
//        bindIntent.putExtra(DEVICE_TOKEN, deviceToken);
        startService(bindIntent);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);

        mHandler.removeCallbacks(webSocketRunnable);
        mHandler.postDelayed(webSocketRunnable, HEART_BEAT_RATE);//开启心跳检测
    }


    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //服务与活动成功绑定
            mWebSocketService = ((WebSocketService.JWebSocketClientBinder) iBinder).getService();
            android.util.Log.e(TAG, "WebSocket服务与Application成功绑定");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //服务与活动断开
            mWebSocketService = null;
            android.util.Log.e(TAG, "WebSocket服务与Application成功断开");
        }
    };

    @Log("启动耗时")
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        initSdk(this);
        // 初始化webSocket Service
//        startWebSocketService();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        // 清理所有图片内存缓存
        GlideApp.get(this).onLowMemory();

    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        // 根据手机内存剩余情况清理图片内存缓存
        GlideApp.get(this).onTrimMemory(level);
    }

    /**
     * 初始化一些第三方框架
     */
    public static void initSdk(Application application) {
        // 设置标题栏初始化器
        TitleBar.setDefaultStyle(new TitleBarStyle());

        // 设置全局的 Header 构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((cx, layout) ->
                new MaterialHeader(application).setColorSchemeColors(ContextCompat.getColor(application, R.color.common_accent_color)));
        // 设置全局的 Footer 构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((cx, layout) -> new SmartBallPulseFooter(application));
        // 设置全局初始化器
        SmartRefreshLayout.setDefaultRefreshInitializer((cx, layout) -> {
            // 刷新头部是否跟随内容偏移
            layout.setEnableHeaderTranslationContent(true)
                    // 刷新尾部是否跟随内容偏移
                    .setEnableFooterTranslationContent(true)
                    // 加载更多是否跟随内容偏移
                    .setEnableFooterFollowWhenNoMoreData(true)
                    // 内容不满一页时是否可以上拉加载更多
                    .setEnableLoadMoreWhenContentNotFull(false)
                    // 仿苹果越界效果开关
                    .setEnableOverScrollDrag(false);
        });

        // 初始化吐司
        ToastUtils.init(application, new ToastStyle());
        // 设置调试模式
        ToastUtils.setDebugMode(AppConfig.isDebug());
        // 设置 Toast 拦截器
        ToastUtils.setInterceptor(new ToastLogInterceptor());

        // Activity 栈管理初始化
        ActivityManager.getInstance().init(application);

        // MMKV 初始化
        MMKV.initialize(application);

        // 网络请求框架初始化
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .build();

        EasyConfig.with(okHttpClient)
                // 是否打印日志
                .setLogEnabled(AppConfig.isLogEnable())
                // 设置服务器配置
                .setServer(new RequestServer())
                // 设置请求处理策略
                .setHandler(new RequestHandler(application))
                // 设置请求重试次数
                .setRetryCount(1)
                .setInterceptor((api, params, headers) -> {
                    MMKV mmkv = MMKV.defaultMMKV();
                    String dataStr = mmkv.getString("loginData", null);
                    if (!TextUtils.isEmpty(dataStr)){
                        Gson gson = new Gson();
                        LoginApi.Bean bean = gson.fromJson(dataStr, LoginApi.Bean.class);
                        if (bean != null && bean.getId() != 0){
                            headers.put("Authorization", "Bearer " + bean.getAccessToken());
                        }
                    }
                    // 添加全局请求头
                    headers.put("versionName", AppConfig.getVersionName());
                    headers.put("versionCode", String.valueOf(AppConfig.getVersionCode()));
                    // 添加全局请求参数
                    // params.put("6666666", "6666666");
                })
                .into();

        // 初始化日志打印
        if (AppConfig.isLogEnable()) {
            Timber.plant(new DebugLoggerTree());
        }

        // 注册网络状态变化监听
        ConnectivityManager connectivityManager = ContextCompat.getSystemService(application, ConnectivityManager.class);
        if (connectivityManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
                @Override
                public void onLost(@NonNull Network network) {
                    Activity topActivity = ActivityManager.getInstance().getTopActivity();
                    if (!(topActivity instanceof LifecycleOwner)) {
                        return;
                    }

                    LifecycleOwner lifecycleOwner = ((LifecycleOwner) topActivity);
                    if (lifecycleOwner.getLifecycle().getCurrentState() != Lifecycle.State.RESUMED) {
                        return;
                    }

                    ToastUtils.show(R.string.common_network_error);
                }
            });
        }

    }
}